<template>
  <a-popover v-model="visible"
             overlayClassName="color-picker-popover"
             trigger="click">
    <component :is="picker"
               v-model="colors"
               slot="content"
               @input="handleValue" />
    <div class="color-picker-handler">
      <div class="color-picker-inner"
           :style="{
             background: colors.hex8 || colors.hex
           }" />
    </div>
  </a-popover>
</template>

<script>

import { Material, Compact, Swatches, Slider, Photoshop, Chrome, Sketch, Twitter, Grayscale } from 'vue-color'
import PropTypes from '@zh/common-utils/prop-types'

export default {
  name: 'ZColorPicker',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    // 选择器类型
    picker: PropTypes.string.def('sketch'),
    defaultValue: PropTypes.string.def('#000000'),
    value: PropTypes.string.def(undefined)
  },
  components: {
    'material': Material,
    'compact': Compact,
    'swatches': Swatches,
    'slider': Slider,
    'photoshop': Photoshop,
    'chrome': Chrome,
    'sketch': Sketch,
    'twitter': Twitter,
    'grayscale': Grayscale
  },
  data () {
    return {
      visible: false,
      colors: {
        color: '',
        hex: '#000000',
        hex8: ''
      }
    }
  },
  created () {
    if (typeof (this.value) === 'string') {
      if (this.value.length > 7) {
        this.colors.hex8 = this.value
      } else {
        this.colors.hex = this.value
      }
    } else if (typeof (this.value) == 'object') {
      this.colors.hex8 = this.value.hex8
      this.colors.hex = this.value.hex8
    } else {
      this.colors.hex = this.defaultValue
    }
  },
  methods: {
    handleValue () {
      if (this.colors.a == 1) {
        this.$emit('change', this.colors.hex, this.colors)
      } else {
        this.$emit('change', this.colors.hex8, this.colors)
      }
    }
  }
}
</script>

<style>
.color-picker-popover .ant-popover-inner-content {
  padding: 0px !important;
}
.ant-popover-inner-content > .vc-sketch {
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0), 0 8px 16px rgba(0, 0, 0, 0);
}
.ant-popover-inner-content .vc-sketch-presets-color {
  border-radius: 0;
  border: 1px solid #bfbfbf;
  box-shadow: none;
}
</style>

<style lang="less" scoped>
.color-picker-handler {
  display: inline-block;
  width: 50px;
  height: 27px;
  border-radius: 2px;
  border: 1px solid #d9d9d9;
  vertical-align: middle;
  padding: 2px;
}
.color-picker-inner {
  width: 100%;
  height: 100%;
  background: #fff;
  border-radius: 2px;
}
</style>